package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 定时任务，对订单进行状态判断
     */
    @ApiOperation("定时任务，对订单进行状态判断")
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void processOutTimeOrder(){
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //查order表 status 状态为1的 且下单时间小于当前时间减15分钟的
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList= ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        //查到了就改mapper中status状态为6
        //update 语句
        if (ordersList != null){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时取消");
                orders.setCancelTime(LocalDateTime.now());
                ordersMapper.update(orders);
            }
        }

    }
    @ApiOperation("派送时长太长凌晨一点更新")
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliverOrder(){
        //查询订单状态为4的订单
        List<Orders> ordersList=ordersMapper.selectByStatus(Orders.DELIVERY_IN_PROGRESS);
        if (ordersList != null){
            for (Orders orders : ordersList){
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                ordersMapper.update(orders);
            }
        }
        //update 语句更新订单状态为5
    }

}
